package com.cnb.telepathytalk.fragment;

import java.util.HashSet;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cnb.telepathytalk.ChoiceActivity;
import com.cnb.telepathytalk.MyProfileViewActivity;
import com.cnb.telepathytalk.ProfileViewActivity;
import com.cnb.telepathytalk.R;
import com.cnb.telepathytalk.TelepathyTalkApplication;
import com.cnb.telepathytalk.adapter.FriendListAdapter;
import com.cnb.telepathytalk.database.PictureIndexDbAdapter;
import com.cnb.telepathytalk.dto.PersonDTO;
import com.cnb.telepathytalk.packet.InterfacePacketBody;
import com.cnb.telepathytalk.packet.PacketHeader;
import com.cnb.telepathytalk.packet.TelepathyPacket;
import com.cnb.telepathytalk.packet.pt10.Packet_PT10_ST02;
import com.cnb.telepathytalk.packet.pt10.Packet_PT10_ST03;
import com.cnb.telepathytalk.packet.pt10.Packet_PT10_ST04;
import com.cnb.telepathytalk.packet.pt10.Packet_PT10_ST71;
import com.cnb.telepathytalk.packet.pt10.Packet_PT10_ST72;
import com.cnb.telepathytalk.packet.pt11.Packet_PT11_ST01;
import com.cnb.telepathytalk.packet.pt11.Packet_PT11_ST02;
import com.emilsjolander.components.stickylistheaders.StickyListHeadersListView;

public class Tab0_Fragment extends Fragment implements AdapterView.OnItemClickListener, android.view.View.OnClickListener {
	private Context mContext;

	private TextView titlebar;
	private StickyListHeadersListView listView;
	private ProgressBar progress;

	private AutoCompleteTextView searchEditText;
	private FriendListAdapter adapter;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mContext = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		adapter = new FriendListAdapter(mContext);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.fragment_tab0, null);

		titlebar = (TextView) view.findViewById(R.id.titlebarText);
		listView = (StickyListHeadersListView) view.findViewById(R.id.listView1);
		progress = (ProgressBar) view.findViewById(R.id.progressBar1);

		TextView rightBtn = (TextView) view.findViewById(R.id.titlebarRightBtn);
		rightBtn.setVisibility(View.VISIBLE);
		rightBtn.setText(R.string.group);
		rightBtn.setOnClickListener(this);

		titlebar.setText(R.string.title_tab0);
		listView.addHeaderView(inflater.inflate(R.layout.search_bar, null));
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);

		searchEditText = (AutoCompleteTextView) view.findViewById(R.id.autoCompleteTextView);
		searchEditText.setAdapter(adapter);

		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		searchEditText.setText("");

		// 친구목록 요청 -> PT11_ST2_Receiver
		requestPT11_ST01();
	}

	@Override
	public void onPause() {
		super.onPause();
		try { // 등록 안한 리시버
			mContext.unregisterReceiver(receiver_PT10_ST4);
		} catch (Exception e) {
		}
		try { // 등록 안한 리시버
			mContext.unregisterReceiver(receiver_PT10_ST72);
		} catch (Exception e) {
		}
		try { // 등록 안한 리시버
			mContext.unregisterReceiver(receiver_PT11_ST2);
		} catch (Exception e) {
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent(mContext, ChoiceActivity.class);
		intent.putExtra(ChoiceActivity.TAG_WHAT, ChoiceActivity.GROUP_CHATING);
		intent.putExtra(ChoiceActivity.TAG_ITEMS, adapter.getList());
		mContext.startActivity(intent);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// 헤더(검색) 떄문에 1감소 시켜야 한다
		arg2--;

		if (adapter.getItem(arg2).getuCode() == TelepathyTalkApplication.uCode) {
			mContext.startActivity(new Intent(mContext, MyProfileViewActivity.class));
		} else {
			Intent intent = new Intent(mContext, ProfileViewActivity.class);
			intent.putExtra(ProfileViewActivity.TAG_OBJECT, adapter.getItem(arg2));
			mContext.startActivity(intent);
		}
	}

	/********************************************************************************
	 * 친구목록 요청
	 */
	/** 친구목록 요청 */
	private void requestPT11_ST01() {
		progress.setVisibility(View.VISIBLE);
		mContext.registerReceiver(receiver_PT11_ST2, new IntentFilter(Packet_PT11_ST02.ID_STRING));

		InterfacePacketBody body = new Packet_PT11_ST01();
		PacketHeader header = new PacketHeader(PacketHeader.SIZE + body.getSize(), TelepathyTalkApplication.appVersion, InterfacePacketBody.PT11,
				InterfacePacketBody.PT11_ST1, TelepathyTalkApplication.uCode);
		TelepathyPacket packet = new TelepathyPacket(header, body);
		packet.threadSendSocket(mContext);
	}

	/** 친구목록 요청 응답 */
	private final BroadcastReceiver receiver_PT11_ST2 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i("receiver_PT11_ST2", "친구요청 목록 응답");
			mContext.unregisterReceiver(receiver_PT11_ST2);

			byte[] data = intent.getByteArrayExtra(Packet_PT11_ST02.ID_STRING);
			Packet_PT11_ST02 body = new Packet_PT11_ST02(data);

			Integer[] uCodes = new Integer[body.getNumber() + 1];
			for (int i = 0; i < body.getNumber(); i++) {
				uCodes[i] = body.getItem(i).getUcode();
			}
			uCodes[body.getNumber()] = TelepathyTalkApplication.uCode;
			requestPT10_ST03(uCodes);
		}
	};

	/********************************************************************************
	 * 다수의 프로필 요청
	 */
	/** 다수의 프로필 요청 */
	private void requestPT10_ST03(Integer[] uCodes) {
		// 다수 프로필 요청 -> receiver_PT10_ST4
		mContext.registerReceiver(receiver_PT10_ST4, new IntentFilter(Packet_PT10_ST04.ID_STRING));

		InterfacePacketBody body1 = new Packet_PT10_ST03(uCodes);
		PacketHeader header = new PacketHeader(PacketHeader.SIZE + body1.getSize(), TelepathyTalkApplication.appVersion, InterfacePacketBody.PT10,
				InterfacePacketBody.PT10_ST3, TelepathyTalkApplication.uCode);
		TelepathyPacket packet = new TelepathyPacket(header, body1);
		packet.threadSendSocket(mContext);
	}

	/** 다수의 프로필 요청 응답 */
	private final BroadcastReceiver receiver_PT10_ST4 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i("receiver_PT10_ST4", "다수의 프로필 요청 응답");
			mContext.unregisterReceiver(receiver_PT10_ST4);

			byte[] data = intent.getByteArrayExtra(Packet_PT10_ST04.ID_STRING);
			Packet_PT10_ST02[] profiles = new Packet_PT10_ST04(data).getProfiles();

			HashSet<Integer> nonFindProfileIndexList = new HashSet<Integer>();

			adapter.setMode(false);
			adapter.getList().clear();
			PictureIndexDbAdapter db = new PictureIndexDbAdapter(mContext).open();
			for (Packet_PT10_ST02 i : profiles) {
				PersonDTO item = new PersonDTO(i.getUcode(), i.getGender(), i.getAge(), i.getProfileIndexs(), i.getName(), i.getStateMsg(),
						i.getIntroMsg(), i.isFriend(), i.isBlock());

				if (item.getProfileIndexArray().length != 0) {
					if (item.getLastProfileIndex() != 0) {
						String profileUrl = db.getAddress(item.getLastProfileIndex());
						if ("".equals(profileUrl)) {
							nonFindProfileIndexList.add(item.getLastProfileIndex());
						} else {
							item.setProfileUrls(0, profileUrl);
						}
					}
				}
				adapter.getList().add(item);
			}
			adapter.sort();

			db.close();
			adapter.notifyDataSetChanged();
			titlebar.setText(mContext.getString(R.string.title_tab0) + "(" + adapter.getList().size() + ")");
			progress.setVisibility(View.GONE);

			// 프로필 사진 요청 -> PT10_ST72_Receiver
			if (nonFindProfileIndexList.size() == 0) {
			} else {
				requestPT10_ST71(nonFindProfileIndexList.toArray(new Integer[0]));
			}
		}
	};

	/************************************************************************************************
	 * 프로필 사진 요청
	 */
	/** 프로필 사진 요청 */
	private void requestPT10_ST71(Integer[] profileIndexArray) {
		mContext.registerReceiver(receiver_PT10_ST72, new IntentFilter(Packet_PT10_ST72.ID_STRING));

		InterfacePacketBody body = new Packet_PT10_ST71(profileIndexArray);
		PacketHeader header = new PacketHeader(PacketHeader.SIZE + body.getSize(), TelepathyTalkApplication.appVersion, InterfacePacketBody.PT10,
				InterfacePacketBody.PT10_ST71, TelepathyTalkApplication.uCode);
		TelepathyPacket packet = new TelepathyPacket(header, body);
		packet.threadSendSocket(mContext);
	}

	/** 프로필 사진 요청 응답 */
	private final BroadcastReceiver receiver_PT10_ST72 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i("PT10_ST72_Receiver", "프로필 사진 요청 응답");
			mContext.unregisterReceiver(receiver_PT10_ST72);

			byte[] data = intent.getByteArrayExtra(Packet_PT10_ST72.ID_STRING);
			Packet_PT10_ST72.Picture[] profilesPics = new Packet_PT10_ST72(data).getProfiles();

			PictureIndexDbAdapter db = new PictureIndexDbAdapter(mContext).open();
			for (int i = 0; i < profilesPics.length; i++) {
				db.insert(profilesPics[i].getIndex(), profilesPics[i].getFileName());
				for (int j = 0; j < adapter.getCount(); j++) {
					if (adapter.getItem(j).getProfileIndex(0) == profilesPics[i].getIndex()) {
						adapter.getItem(j).setProfileUrls(0, profilesPics[i].getFileName());
					}
				}
			}
			db.close();

			adapter.notifyDataSetChanged();
		}
	};
}